<template>
  <div>
    <van-nav-bar title="详情" left-arrow @click-left="onClickLeft" />
    <template v-if="item.urls">
      <Banner :images="item.urls" />
    </template>
    <h1>{{ item.title }}</h1>
    <p>{{ item.desc }}</p>
    <h4 style="color:red">￥{{ item.price }}</h4>

    <!-- 底部加入购物车 -->
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon icon="cart-o" text="购物车" @click="$router.push('/home/car')" :badge="totalCounter"/>
      <van-action-bar-icon icon="shop-o" text="店铺" />
      <van-action-bar-button
        type="danger"
        text="加入购物车"
        @click="addCar"
      />
    </van-action-bar>
  </div>
</template>


<script>
import { computed, onMounted, ref } from "vue";
import request from "@/utils/api";
import { useRoute, useRouter } from "vue-router";
import Banner from "@/components/Banner";
export default {
  name: "Detail",
  components: {
    Banner
  },
  setup() {
    // 当前路由
    const route = useRoute();
    // 导航路由
    const router = useRouter();

    // 详情数据
    const item = ref({});

    const car = ref(JSON.parse(localStorage.getItem('car')) || [])


    const totalCounter = computed(() => {
      let count = 0
      car.value.forEach(v => {
        count += v.count
      })

      return count
    })

    // 请求详情的方法
    const getDetail = async id => {
      // 请求详情
      const resp = await request.post("/api/detail", { id });
      // 修改数据
      item.value = resp.data.data;
    };
    // 返回上一页
    const onClickLeft = () => {
      router.back();
    };
    // 加入购物车
    const addCar = () => {
      /**
       * 1. 获取本地购物车数据
       * 
       * 2. 需要验证加入的数据 是否 存在于 本地购物车数据  （id  去重）
       *    2-1  存在数量递增
       *    2-2  不存在 添加新数据  数量为1
       * 3. 保存本地储存
       * 
       * 
      */
     

      const o = car.value.find(v => v.id === item.value.id)

      if(o) {
        o.count++
      } else {
        car.value.push({
          ...item.value,
          // 数量
          count: 1,
          // 是否选中
          isChecked: false
        })
      }

      localStorage.setItem('car', JSON.stringify(car.value))
    }


    // 声明周期
    onMounted(() => {
      // 获取动态路由参数 id
      const { id } = route.params;
      //请求数据
      getDetail(id);
    });

    return {
      item,
      onClickLeft,
      addCar,
      totalCounter
    };
  }
};
</script>